'use strict'

import React, { Component } from 'react'
import noop from 'lodash/noop'

import * as color from '../../configs/color'

const toastStyle = {
    position: 'fixed',
    zIndex: '299',
    top: '36%',
    left: '20px',
    right: '20px',
    padding: '15px',
    fontSize: '16px',
    textAlign: 'center',
    lineHeight: '20px',
    color: color.WHITE,
    backgroundColor: color.TOAST,
    borderRadius: '5px'
}

export default class Toast extends Component {
    constructor(props) {
        super(props)
        this.state = {
            on: this.props.on
        }
        this.dismiss = this.dismiss.bind(this)
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            on: nextProps.on
        })
    }

    dismiss() {
        this.setState({
            on: false
        }, () => {
            this.props.onDismiss()
        })
    }

    componentDidMount() {
        if (this.state.on) {
            setTimeout(this.dismiss, this.props.duration * 1000)
        }
    }

    componentDidUpdate() {
        if (this.state.on) {
            setTimeout(this.dismiss, this.props.duration * 1000)
        }
    }

    render() {
        const renderStyle = Object.assign({}, toastStyle, {
            display: this.state.on ? 'block' : 'none'
        })
        return (
            <div style={renderStyle}>
                {this.props.message}
            </div>
        )
    }
}

Toast.defaultProps = {
    type: '',
    on: false,
    delay: 0,
    duration: 3,
    message: '',
    onDismiss: noop
}

Toast.propTypes = {
    type: React.PropTypes.string,
    on: React.PropTypes.bool,
    delay: React.PropTypes.number,
    duration: React.PropTypes.number,
    message: React.PropTypes.string,
    onDismiss: React.PropTypes.func
}